package com.example.hyg_veintype.activity.bleList;

import android.animation.ObjectAnimator;
import android.animation.ValueAnimator;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.animation.LinearInterpolator;
import android.widget.Button;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.hyg_veintype.R;
import com.example.hyg_veintype.activity.bleConnect2.ConnectBLE2Activity;
import com.example.hyg_veintype.activity.bleList.adapter.BlueToothListAdapter;
import com.example.hyg_veintype.base.BaseVeinTypeActivity;
import com.example.hyg_veintype.constant.ble.BleRssiDevice;
import com.example.hyg_veintype.constant.ble.PreBLEConnectedData;
import com.google.android.material.floatingactionbutton.FloatingActionButton;

import java.util.LinkedList;

import cn.com.heaton.blelibrary.ble.Ble;
import cn.com.heaton.blelibrary.ble.BleLog;
import cn.com.heaton.blelibrary.ble.callback.BleScanCallback;
import cn.com.heaton.blelibrary.ble.callback.BleStatusCallback;
import cn.com.heaton.blelibrary.ble.model.ScanRecord;
import cn.com.heaton.blelibrary.ble.utils.Utils;

/**
 * @author: yyw
 * time: 2020/12/11 13:15
 * desc:蓝牙扫描列表页面
 */
public class ScanBLEListActivity extends BaseVeinTypeActivity {
    private final String TAG = "MainActivity";
    public static final int REQUEST_GPS = 4;

    RecyclerView rvBleList;
    FloatingActionButton btScan;
    Button btConnect;

    /**
     * 蓝牙列表适配器
     */
    BlueToothListAdapter adapter;
    /**
     * 蓝牙列表数据
     */
    LinkedList<BleRssiDevice> bleRssiDevices = new LinkedList<>();
    /**
     * 对外提供所有的蓝牙操作接口.
     */
    private Ble<BleRssiDevice> ble = Ble.getInstance();
    /**
     * 转圈动画
     */
    private ObjectAnimator animator;

    /**
     * 上次连接过的蓝牙ID
     */
    private String preConnectedBLEId = "";

    public static void start(Context context) {
        Intent starter = new Intent(context, ScanBLEListActivity.class);
        context.startActivity(starter);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.veintype_activity_scan_ble_list;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        tvTitle.setText("蓝牙列表");
        initView();
        initAdapter();
        initBleStatus();
        rescan();
    }

    private void initView() {
        rvBleList = findViewById(R.id.rv_ble_list);
        btScan = findViewById(R.id.bt_scan);
        btScan.setOnClickListener(this);
        btConnect = findViewById(R.id.bt_connect);
        btConnect.setOnClickListener(this);
    }

    @Override
    protected void onResume() {
        super.onResume();
        preConnectedBLEId = PreBLEConnectedData.getLocalBLEDevice(this);
    }

    @Override
    protected void onStop() {
        super.onStop();
        stopScan();
    }

    /**
     * 蓝牙列表初始化
     */
    private void initAdapter() {
        adapter = new BlueToothListAdapter(bleRssiDevices, btConnect, this);
        rvBleList.setLayoutManager(new LinearLayoutManager(this));
        rvBleList.setAdapter(adapter);
    }

    @Override
    public void onClick(View view) {
        int id = view.getId();
        if (id == R.id.bt_scan) {//扫描
            rescan();
        } else if (id == R.id.bt_connect) {
            stopScan();
            jumpConncetActivity();
            //连接
        }
    }

    /**
     * 跳转连接页面
     */
    private void jumpConncetActivity() {
        int index = -1;
        for (int i = 0; i < bleRssiDevices.size(); i++) {
            if (bleRssiDevices.get(i).isChecked()) {
                index = i;
                break;
            }
        }
        if (index != -1) {
            ConnectBLE2Activity.start(ScanBLEListActivity.this, bleRssiDevices.get(index));
//            ConnectBLEActivity.start(ScanBLEListActivity.this, bleRssiDevices.get(index));
            finish();
        }
    }

    /**
     * 监听蓝牙开关状态
     */
    private void initBleStatus() {
        ble.setBleStatusCallback(new BleStatusCallback() {
            @Override
            public void onBluetoothStatusChanged(boolean isOn) {
                BleLog.i(TAG, "onBluetoothStatusOn: 蓝牙是否打开>>>>:" + isOn);
                if (isOn) {
                    checkGpsStatus();
                } else {
                    if (ble.isScanning()) {
                        ble.stopScan();
                    }
                }
            }
        });
    }

    /**
     * 检查蓝牙是否打开
     */
    private void checkGpsStatus() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M
                && !Utils.isGpsOpen(ScanBLEListActivity.this)) {
            new AlertDialog.Builder(ScanBLEListActivity.this)
                    .setTitle("提示")
                    .setMessage("为了更精确的扫描到Bluetooth LE设备,请打开GPS定位")
                    .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                            startActivityForResult(intent, REQUEST_GPS);
                        }
                    })
                    .setNegativeButton("取消", null)
                    .create()
                    .show();
        } else {
            ble.startScan(scanCallback);
        }
    }

    /**
     * 蓝牙扫描监听
     */
    private BleScanCallback<BleRssiDevice> scanCallback = new BleScanCallback<BleRssiDevice>() {
        @Override
        public void onLeScan(final BleRssiDevice device, int rssi, byte[] scanRecord) {
            if (TextUtils.isEmpty(device.getBleName())) return;

            synchronized (ble.getLocker()) {
                for (int i = 0; i < bleRssiDevices.size(); i++) {
                    BleRssiDevice rssiDevice = bleRssiDevices.get(i);
                    if (TextUtils.equals(rssiDevice.getBleAddress(), device.getBleAddress())) {
                        if (rssiDevice.getRssi() != rssi && System.currentTimeMillis() - rssiDevice.getRssiUpdateTime() > 1000L) {
                            rssiDevice.setRssiUpdateTime(System.currentTimeMillis());
                            rssiDevice.setRssi(rssi);
                            adapter.notifyItemChanged(i);
                        }
                        return;
                    }
                }
                device.setScanRecord(ScanRecord.parseFromBytes(scanRecord));
                device.setRssi(rssi);
                //判断蓝牙是否连接过，连接过的蓝牙选中并放在顶部
                if (TextUtils.equals(preConnectedBLEId, device.getBleAddress())) {
                    for (BleRssiDevice bleRssiDevice : bleRssiDevices) {
                        bleRssiDevice.setChecked(false);
                    }
                    device.setChecked(true);
                    bleRssiDevices.addFirst(device);
                } else {
                    device.setChecked(false);
                    bleRssiDevices.add(device);
                }
                adapter.notifyDataSetChanged();
            }
        }

        @Override
        public void onStart() {
            super.onStart();
            startBannerLoadingAnim();
        }

        @Override
        public void onStop() {
            super.onStop();
            stopBannerLoadingAnim();
        }

        @Override
        public void onScanFailed(int errorCode) {
            super.onScanFailed(errorCode);
            Log.e(TAG, "onScanFailed: " + errorCode);
        }
    };

    /**
     * 开始动画
     */
    public void startBannerLoadingAnim() {
        btScan.setImageResource(R.drawable.ic_loading);
        animator = ObjectAnimator.ofFloat(btScan, "rotation", 0, 360);
        animator.setRepeatCount(ValueAnimator.INFINITE);
        animator.setDuration(800);
        animator.setInterpolator(new LinearInterpolator());
        animator.start();
    }

    /**
     * 停止动画
     */
    public void stopBannerLoadingAnim() {
        btScan.setImageResource(R.drawable.veintype_ic_ble_ani);
        animator.cancel();
        btScan.setRotation(0);
    }

    /**
     * 清空蓝牙列表数据并重新扫描
     */
    private void rescan() {
        if (ble != null && !ble.isScanning()) {
            bleRssiDevices.clear();
            adapter.notifyDataSetChanged();
            ble.startScan(scanCallback);
        }
    }

    /**
     * 停止扫描
     */
    private void stopScan() {
        if (ble != null && ble.isScanning()) {
            ble.stopScan();
        }
    }
}